// pages/index5/index5.js
const {
  getUserById, isLikePost, recommendedVideo, likePost, disLikePost
} = require('../../apis/api')

import { createStoreBindings } from 'mobx-miniprogram-bindings'
import { store } from '../../store/store'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    viList: [

    ],
    videoId: null
  },
  comment(event) {
    if (this.data.videoId) {
      // 创建控制video标签的实例对象
      this.videoContextPrev = wx.createVideoContext(this.data.videoId)
      // 关闭当前播放的视频
      this.videoContextPrev.stop()
    }
    wx.navigateTo({
      url: '/pages/detail/detail?nid=' + event.currentTarget.dataset.nid,
    })
  },
  handlerPlay(event) {
    // 获取当前视频的id
    let vid = event.currentTarget.id
    if (!this.data.videoId) {
      // 更新data中的videoId的状态数据
      this.setData({
        videoId: vid
      })
      let videoContext2 = wx.createVideoContext(vid)
      videoContext2.play()
    } else {
      this.setData({
        videoId: vid
      })
      // 创建控制video标签的实例对象
      this.videoContextPrev = wx.createVideoContext(this.data.videoId)
      // 关闭当前播放的视频
      this.videoContextPrev.stop()
      this.timer1 = setTimeout(() => {
        let videoContext2 = wx.createVideoContext(vid)
        videoContext2.play()
      }, 200)
    }


    // // 判断当前视屏是否有播放记录，如果有，跳转至指定播放位置
    // let { videoUpdateTime } = this.data
    // let videoItem = videoUpdateTime.find(item => item.vid === vid)
    // // 情况一：如果有播放记录，从记录处继续播放
    // if (videoItem) {
    //     // 获取播放的时间点，单位/s
    //     let timepoint = videoItem.currentTime
    //     this.timer1 = setTimeout(() => {
    //         let videoContext1 = wx.createVideoContext(vid)
    //         // 跳转到指定的时间位置
    //         videoContext1.seek(timepoint)
    //         videoContext1.play()
    //     }, 200)
    // }
    // // 情况二：如果没有播放记录，开始新的播放
    // else {
    //     this.timer2 = setTimeout(() => {
    //         let videoContext2 = wx.createVideoContext(vid)
    //         videoContext2.play()
    //     }, 200)
    // }
  },

  // // 监听视频播放进度的回调
  // handleTimeUpdate(event) {
  //     let { videoUpdateTime } = this.data
  //     let videoTimeObj = {
  //         vid: event.currentTarget.id,
  //         currentTime: event.detail.currentTime
  //     }
  //     /* 
  //       判断记录播放时长的videoUpdateTime数组中是否有当前视频的播放记录
  //       如果有修改原有播放记录，如果没有需要在数组中添加当前视频的播放记录
  //     */
  //     let videoItem = videoUpdateTime.find(item => item.vid === videoTimeObj.vid);
  //     if (videoItem) { // 之前有播放记录
  //         videoItem.currentTime = videoTimeObj.currentTime;
  //     } else { // 之前没有播放记录
  //         videoUpdateTime.push(videoTimeObj);
  //     }
  //     // 更新videoUpdateTime的状态
  //     this.setData({
  //         videoUpdateTime
  //     })
  // },

  // 视频播放结束调用的回调
  handleEnded(event) {

    this.setData({

      // 这里将videoId重置，使页面渲染的视频均为image封面图覆盖
      videoId: ''
    })
  },
  onLoad(options) {
    this.storeBindings = createStoreBindings(this, {
      store,
      fields: ['username', 'userAvatar', 'email', 'token'],
      actions: ['setUsername', 'setUserAvatar', 'setEmail', 'setToken'],
    })
  },
  onReady() {
    this.getrecommendedVideo()
  },
  getrecommendedVideo() {
    wx.showLoading({  // 显示加载中loading效果 
      title: "加载中",
      mask: true  //开启蒙版遮罩
    });
    recommendedVideo(this.data.token, (res) => {
      if (res.data.code === 200) {

        var arr = res.data.data.map((item) => {
          return new Promise((resolve) => {
            getUserById(this.data.token, item.post_owner_id, (res) => {
              if (res.data.code === 200) {
                resolve({
                  ...item,
                  tx: res.data.data.pictureUrl,
                  name: res.data.data.userName,
                });
              } else {
                wx.showToast({
                  title: res.data.message,
                  icon: 'none',
                });
                resolve(item); // Return the original item in case of error.
              }
            });
          });
        });
        Promise.all(arr).then((updatedData) => {
          this.setData({
            viList: updatedData,
          });

          // 在此处处理 isLikePost 请求
          const likePromises = this.data.viList.map((item) => {
            return new Promise((resolve) => {
              isLikePost(this.data.token, item.post_id, (res) => {
                if (res.data.code === 200) {
                  resolve({
                    ...item,
                    love: res.data.data === 'true' ? true : false
                  });
                } else {
                  wx.showToast({
                    title: res.data.message,
                    icon: 'none',
                  });
                  resolve(item); // Return the original item in case of error.
                }
              });
            });
          });

          Promise.all(likePromises).then((updatedDataWithLikes) => {
            this.setData({
              viList: updatedDataWithLikes,
            });
            wx.hideLoading()
            console.log(this.data.viList);
          });
        });
      } else {
        wx.showToast({
          title: res.data.message,
          icon: 'none'
        });
      }
    });
  },
  changeLike(e) {
    console.log("love", e.currentTarget.dataset)
    const index = e.currentTarget.dataset.index
    if (this.data.viList[index].love) {
      var num = this.data.viList[index].likes;
      this.data.viList[index].love = false,
        this.data.viList[index].likes = (num - 1)
      this.setData({
        viList: this.data.viList
      })
      disLikePost(this.data.token, e.currentTarget.dataset.nid, (res) => {
        if (res.data.code === 200) {
          console.log(this.data.viList)
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none',
          });
        }
      })
    } else {
      var num = this.data.viList[index].likes;
      this.data.viList[index].love = true,
      this.data.viList[index].likes = (num + 1)

      this.setData({
        viList: this.data.viList
      })
      likePost(this.data.token, e.currentTarget.dataset.nid, (res) => {
        if (res.data.code === 200) {
          console.log(this.data.viList)
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none',
          });
        }
      })
    }
  },

  // // 进页面时播放视频
  // startUp() {
  //   // 获取video节点
  //   let createVideoContext = wx.createVideoContext('video0')
  //   // 播放视频
  //   createVideoContext.play()
  // },

  // // 切换视频的时候播放视频
  // // 注：此方法视频如果过大可能会叠音，所以视频需要压缩，或者可以尝试循环节点关闭视频
  // nextVideo(e){
  //   // 播放当前页面视频
  //   let index = 'video' + e.detail.current
  //   this.playVio(index)
  //   // 暂停前一个页面视频
  //   if(e.detail.current-1 >= 0){
  //     let index1 = 'video' + (e.detail.current-1)
  //     this.pauseVio(index1)
  //   }
  //   // 暂停后一个页面视频
  //   if(e.detail.current+1 < this.data.viList.length){
  //     let index2 = 'video' + (e.detail.current+1)
  //     this.pauseVio(index2)
  //   }
  // },

  // 播放视频
  playVio(index) {
    // 获取video节点
    let createVideoContext = wx.createVideoContext(index.currentTarget.id)
    // 播放视频
    createVideoContext.play()
  },

  // 暂停视频
  pauseVio(index) {
    console.log(index.currentTarget.id)
    // 获取video节点
    let createVideoContext = wx.createVideoContext(index.currentTarget.id)
    // 暂停视频
    createVideoContext.pause()
  }
})